package com.mujin.keji.collectionsystem.module.tripplan.views;

import android.Manifest;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.bikenavi.BikeNavigateHelper;
import com.baidu.mapapi.bikenavi.adapter.IBEngineInitListener;
import com.baidu.mapapi.bikenavi.adapter.IBRoutePlanListener;
import com.baidu.mapapi.bikenavi.model.BikeRoutePlanError;
import com.baidu.mapapi.bikenavi.params.BikeNaviLaunchParam;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.walknavi.WalkNavigateHelper;
import com.baidu.mapapi.walknavi.adapter.IWEngineInitListener;
import com.baidu.mapapi.walknavi.adapter.IWRoutePlanListener;
import com.baidu.mapapi.walknavi.model.WalkRoutePlanError;
import com.baidu.mapapi.walknavi.params.WalkNaviLaunchParam;
import com.baidu.navisdk.adapter.BNCommonSettingParam;
import com.baidu.navisdk.adapter.BNOuterTTSPlayerCallback;
import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BNaviSettingManager;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.baidu.platform.comapi.walknavi.widget.ArCameraView;
import com.mujin.keji.collectionsystem.CcsApplication;
import com.mujin.keji.collectionsystem.Constant;
import com.mujin.keji.collectionsystem.R;
import com.mujin.keji.collectionsystem.base.BaseActivity;
import com.mujin.keji.collectionsystem.base.BaseDto;
import com.mujin.keji.collectionsystem.listeners.CustomItemClickListener;
import com.mujin.keji.collectionsystem.module.tripplan.adapter.SelectPersionAdapter;
import com.mujin.keji.collectionsystem.module.tripplan.dto.QueryPlanDetailDto;
import com.mujin.keji.collectionsystem.module.tripplan.dto.QueryPlanDetailListDto;
import com.mujin.keji.collectionsystem.module.tripplan.dto.QueryPlanDto;
import com.mujin.keji.collectionsystem.module.tripplan.viewmodel.TripPlanViewModel;
import com.mujin.keji.collectionsystem.module.tripplan.vo.LatLonVo;
import com.mujin.keji.collectionsystem.net.NetworkUtil;
import com.mujin.keji.collectionsystem.permissions.PermissionUtils;
import com.mujin.keji.collectionsystem.permissions.PermissionsObserver;
import com.mujin.keji.collectionsystem.receiver.SDKReceiver;
import com.mujin.keji.collectionsystem.utils.DialogUtils;
import com.mujin.keji.collectionsystem.utils.DistanceUtil;
import com.mujin.keji.collectionsystem.utils.EmptyUtils;
import com.mujin.keji.collectionsystem.utils.ToastUtils;
import com.mujin.keji.collectionsystem.widget.SelectTrrificPopWindow;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.zhy.m.permission.MPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 百度地图实现动态路线规划Activity界面
 *
 * @author weishixiong
 * @Time 2018-03-22
 */

public class TaskTripMapActivity extends BaseActivity implements BDLocationListener, View.OnClickListener, CustomItemClickListener, SelectTrrificPopWindow.SelectLisenter {

    // 定义搜索服务类
    private GeoCoder mSearch;
    private double currentLat;//当前位置的维度
    private double currentLon;//当前位置的维度
    private double targetLat;//目标位置的经度
    private double targetLon;//目标位置的经度
    //当前位置名称
    private String currentAdress;
    //地图对象
    private BaiduMap baiduMap;
    //需要的权限列表
    private final static String authBaseArr[] =
            {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
    private String mSDCardPath = null;
    private String authinfo = null;
    private static final String APP_FOLDER_NAME = "app_folder_name";
    private WalkNavigateHelper walkNavigateHelper;
    private WalkNaviLaunchParam walkNaviLaunchParam;
    private BikeNaviLaunchParam bikeNaviLaunchParam;
    private BikeNavigateHelper bikeNavigateHelper;
    private SDKReceiver mReceiver;
    private QueryPlanDto mQueryPlanDto;
    private MapView bmapView;
    private TextView tvName;
    private TextView tvRelationship;
    private TextView tvAdress;
    private TextView tvDistance;
    private RecyclerView rvVisitors;
    private ImageView ivToTrip;
    //   private NavigationView navigationView;
    private TripPlanViewModel tripPlanViewModel;
    private List<QueryPlanDetailDto> lists;
    private LinearLayoutManager linearLayoutManager;
    private SelectPersionAdapter selectPersionAdapter;
    private List<LatLng> mPointList;//目标经纬度集合
    private LinearLayout llBottom;


    /**
     * 初始化 行程规划详情
     */
    private void initQueryPlanDetail() {
        getLoadingDialog().showDialog();
        tripPlanViewModel.queryPlanDetail(mQueryPlanDto.getId()).observe(this, new Observer<BaseDto<QueryPlanDetailListDto>>() {
            @Override
            public void onChanged(@Nullable BaseDto<QueryPlanDetailListDto> queryPlanDetailListDtoBaseDto) {
                getLoadingDialog().dismiss();
                if (EmptyUtils.isNotEmpty(queryPlanDetailListDtoBaseDto.getData()) && EmptyUtils.isNotEmpty(queryPlanDetailListDtoBaseDto.getData().getLists())) {
                    lists.clear();
                    QueryPlanDetailDto queryPlanDetailDto = new QueryPlanDetailDto();
                    queryPlanDetailDto.setSelected(true);
                    lists.add(queryPlanDetailDto);
                    lists.addAll(queryPlanDetailListDtoBaseDto.getData().getLists());
                    selectPersionAdapter.notifyDataSetChanged();
                    /**
                     * 初始化拜访的目标点
                     * 并展示在地图上
                     */
                    initVisitTarget();
                }

            }
        });

    }

    @Override
    protected void createViewModel() {
        tripPlanViewModel = ViewModelProviders.of(this).get(TripPlanViewModel.class);
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_tasktripmap;
    }

    @Override
    public void initView() {
        contentView = getWindow().getDecorView();
        setCenterTitle("行程规划", "#FFFFFF");
        setleftImage(R.drawable.image_arrow_left_white, true, null);
        bmapView = (MapView) findViewById(R.id.bmapView);
        tvName = (TextView) findViewById(R.id.tv_name);
        tvRelationship = (TextView) findViewById(R.id.tv_relationship);
        llBottom = (LinearLayout) findViewById(R.id.ll_bottom);
        tvAdress = (TextView) findViewById(R.id.tv_adress);
        tvDistance = (TextView) findViewById(R.id.tv_distance);
        rvVisitors = (RecyclerView) findViewById(R.id.rv_visitors);
        ivToTrip = (ImageView) findViewById(R.id.iv_to_trip);
        baiduMap = bmapView.getMap();
        lists = new ArrayList<>();
        linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);// 横向滑动
        rvVisitors.setLayoutManager(linearLayoutManager);
        selectPersionAdapter = new SelectPersionAdapter(this, lists, this);
        rvVisitors.setAdapter(selectPersionAdapter);
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.zoom(18.0f);//这里设置了缩放的比例，float类型。
        baiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
    }

    @Override
    public void initData() {
        /**
         * 初始化GeoCoder对象，用于把经纬度坐标转换成adress
         */
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(listener);
        icons = new ArrayList<>();
        icons.add(R.drawable.image_my_location);
        icons.add(R.drawable.image_one);
        icons.add(R.drawable.image_two);
        icons.add(R.drawable.image_three);
        icons.add(R.drawable.image_four);
        icons.add(R.drawable.image_five);
        icons.add(R.drawable.image_six);
        icons.add(R.drawable.image_seven);
        icons.add(R.drawable.image_eight);
        icons.add(R.drawable.image_nine);
        icons.add(R.drawable.image_ten);
        icons.add(R.drawable.image_location_default);
        //打开位置设置界面
        getLocationSetting();
        /**
         * 获取需要的权限，电话，定位，存储权限
         * 用于初始化驾车导航
         * 相机权限，用于步行导航
         */
        requestPermissions();


    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    /**
     * 打开位置设置
     */
    private void getLocationSetting() {
        if (!NetworkUtil.isGpsOPen(this)) {
            CcsApplication.getInstance().mLocationClient.stop();
            //位置信息没有开启
            DialogUtils.showAdressInfoDailog("无法获取当前位置信息，请在手机设置中开启位置信息", TaskTripMapActivity.this);
            //Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            //startActivity(intent);

            return;
        }
    }

    private boolean initDirs() {
        mSDCardPath = getSdcardDir();
        if (mSDCardPath == null) {
            return false;
        }
        File f = new File(mSDCardPath, APP_FOLDER_NAME);
        if (!f.exists()) {
            try {
                f.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    /**
     * 内部TTS播报状态回调接口
     */
    private BaiduNaviManager.TTSPlayStateListener ttsPlayStateListener = new BaiduNaviManager.TTSPlayStateListener() {

        @Override
        public void playEnd() {
            // showToastMsg("TTSPlayStateListener : TTS play end");
        }

        @Override
        public void playStart() {
            // showToastMsg("TTSPlayStateListener : TTS play start");
        }

    };

    /**
     * 内部TTS播报状态回传handler
     */
    private Handler ttsHandler = new Handler() {
        public void handleMessage(Message msg) {
            int type = msg.what;
            switch (type) {
                case BaiduNaviManager.TTSPlayMsgType.PLAY_START_MSG: {
                    break;
                }
                case BaiduNaviManager.TTSPlayMsgType.PLAY_END_MSG: {
                    break;
                }
                default:
                    break;
            }
        }
    };

    private void initSetting() {
        BNaviSettingManager.setDayNightMode(BNaviSettingManager.DayNightMode.DAY_NIGHT_MODE_DAY);
        BNaviSettingManager
                .setShowTotalRoadConditionBar(BNaviSettingManager.PreViewRoadCondition.ROAD_CONDITION_BAR_SHOW_ON);
        BNaviSettingManager.setVoiceMode(BNaviSettingManager.VoiceMode.Veteran);
        // BNaviSettingManager.setPowerSaveMode(BNaviSettingManager.PowerSaveMode.DISABLE_MODE);
        BNaviSettingManager.setRealRoadCondition(BNaviSettingManager.RealRoadCondition.NAVI_ITS_ON);
        BNaviSettingManager.setIsAutoQuitWhenArrived(true);
        Bundle bundle = new Bundle();
        // 必须设置APPID，否则会静音
        bundle.putString(BNCommonSettingParam.TTS_APP_ID, "10986773");
        BNaviSettingManager.setNaviSdkParam(bundle);
    }

    private String getSdcardDir() {
        if (Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
            return Environment.getExternalStorageDirectory().toString();
        }
        return null;
    }

    /**
     * 初始化拜访的目标点
     * 并展示在地图上
     */
    private void initVisitTarget() {
        mPointList = new ArrayList<>();
        for (int i = 0; i < lists.size(); i++) {
            if (i == 0) {
                mPointList.add(new LatLng(currentLat, currentLon));
            } else {
                mPointList.add(lists.get(i).getLatLng());
            }

        }
        //展示在地图上
        showPointsInBaiduMap(mPointList, null);
        //初始化第一个人的底部ui数据
        initBottomView(0);

    }

    private Integer status;
    private String addressCity;
    private QueryPlanDetailDto queryPlanDetailDto;


    /**
     * 展示底部视图，并定位到目标点
     *
     * @param position
     */
    private void initBottomView(int position) {
        //如果点击的是同一个
        if (isSamePoint(position)) {
            //继续描绘这个点
            List<LatLng> p = new ArrayList<>();
            p.add(mPointList.get(position));
            showPointsInBaiduMap(p, icons.get(position));
        }
        //并定位到目标
        initMapLocation(mPointList.get(position).latitude, mPointList.get(position).longitude);
        if (position == 0) {
            llBottom.setVisibility(View.GONE);
            ivToTrip.setVisibility(View.GONE);
        } else {
            llBottom.setVisibility(View.VISIBLE);
            ivToTrip.setVisibility(View.VISIBLE);
            queryPlanDetailDto = lists.get(position);
            status = lists.get(position).getStatus();
            addressCity = lists.get(position).getAddressCity();
            tvName.setText(lists.get(position).getVisitName());
            targetLat = mPointList.get(position).latitude;
            targetLon = mPointList.get(position).longitude;
            //获取当前点距目标点的距离
            tvDistance.setText(DistanceUtil.getDistance(currentLat, currentLon, mPointList.get(position).latitude, mPointList.get(position).longitude));
            tvRelationship.setText(lists.get(position).getVisitRelation());
            tvAdress.setText(lists.get(position).getVisitAddress());
        }

    }

    /**
     * 点击的点  是否包含了同一个点
     */
    private boolean isSame = false;

    /**
     * 判断是否是同一个点
     *
     * @param position
     * @return
     */
    private boolean isSamePoint(int position) {
        isSame = false;
        if (EmptyUtils.isNotEmpty(mPointList)) {
            for (int i = 0; i < mPointList.size(); i++) {
                if (
                        i != position
                                &&
                                mPointList.get(i).latitude == mPointList.get(position).latitude
                                && mPointList.get(i).longitude == mPointList.get(position).longitude
                        ) {
                    isSame = true;
                    break;
                }
            }

        }
        return isSame;

    }

    //获取定位权限，存储权限，电话权限
    private void requestPermissions() {
        RxPermissions.getInstance(this).request(
                Manifest.permission.RECORD_AUDIO,//录音权限
                Manifest.permission.ACCESS_COARSE_LOCATION, //定位权限
                Manifest.permission.ACCESS_FINE_LOCATION,//定位权限
                Manifest.permission.WRITE_EXTERNAL_STORAGE,//写权限
                Manifest.permission.READ_EXTERNAL_STORAGE, //读权限
                Manifest.permission.READ_PHONE_STATE,//电话权限
                Manifest.permission.CAMERA//相机权限
        ).subscribe(new PermissionsObserver() {
            @Override
            protected void onGetPermissionsSuccess() {
                //获取定位地址
                startLocationCilent();
                /**
                 * 初始化车驾驶导航
                 */
                if (initDirs()) {
                    initNavi();
                }
            }

            @Override
            protected void onGetPermissionsSuccessFailuer() {
                if (!PermissionUtils.hasPermission(TaskTripMapActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION})) {
                    DialogUtils.showPerMissionDailog(Constant.FINALVALUE.LOCATION_MESSAGE, TaskTripMapActivity.this);
                    return;
                }
                if (!PermissionUtils.hasPermission(TaskTripMapActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION})) {
                    DialogUtils.showPerMissionDailog(Constant.FINALVALUE.LOCATION_MESSAGE, TaskTripMapActivity.this);
                    return;
                }

                if (!PermissionUtils.hasPermission(TaskTripMapActivity.this, new String[]{Manifest.permission.CAMERA})) {
                    DialogUtils.showPerMissionDailog(Constant.FINALVALUE.CAMERA_MESSAGE, TaskTripMapActivity.this);
                    return;
                }
                if (!PermissionUtils.hasPermission(TaskTripMapActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE})) {
                    DialogUtils.showPerMissionDailog(Constant.FINALVALUE.EXTERNAL_MESSAGE, TaskTripMapActivity.this);
                    return;
                }
                if (!PermissionUtils.hasPermission(TaskTripMapActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE})) {
                    DialogUtils.showPerMissionDailog(Constant.FINALVALUE.EXTERNAL_MESSAGE, TaskTripMapActivity.this);
                    return;
                }
                if (!PermissionUtils.hasPermission(TaskTripMapActivity.this, new String[]{Manifest.permission.RECORD_AUDIO})) {
                    DialogUtils.showPerMissionDailog(Constant.FINALVALUE.RECORD_MESSAGE, TaskTripMapActivity.this);
                    return;
                }
                if (!PermissionUtils.hasPermission(TaskTripMapActivity.this, new String[]{Manifest.permission.READ_PHONE_STATE})) {
                    DialogUtils.showPerMissionDailog(Constant.FINALVALUE.PHONE_MESSAGE, TaskTripMapActivity.this);
                    return;
                }
            }
        });
    }

    /**
     * 初始化驾车导航相关配置
     */
    private void initNavi() {
        BNOuterTTSPlayerCallback ttsCallback = null;
        //检查权限
        if (!PermissionUtils.hasPermission(this, authBaseArr)) {
            requestPermissions();
            return;
        }
        //初始化导航相关
        BaiduNaviManager.getInstance().init(this, mSDCardPath, APP_FOLDER_NAME, new BaiduNaviManager.NaviInitListener() {
            @Override
            public void onAuthResult(int status, String msg) {
                if (0 == status) {
                    authinfo = "key校验成功!";
                } else {
                    authinfo = "key校验失败, " + msg;
                }
                TaskTripMapActivity.this.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                    }
                });
            }

            public void initSuccess() {
                initSetting();
            }

            public void initStart() {
            }

            public void initFailed() {
            }

        }, null, ttsHandler, ttsPlayStateListener);

    }

    /**
     * 初始化步行导航
     */
    private void initWalkNavi() {
        walkNavigateHelper = WalkNavigateHelper.getInstance();
        walkNaviLaunchParam = new WalkNaviLaunchParam().stPt(new LatLng(currentLat, currentLon)).endPt(new LatLng(targetLat, targetLon));
        // 获取导航控制类
        walkNavigateHelper = WalkNavigateHelper.getInstance();
    }

    /**
     * 初始化自行车导航
     */
    private void initBikeNavi() {
        bikeNaviLaunchParam = new BikeNaviLaunchParam().stPt(new LatLng(currentLat, currentLon)).endPt(new LatLng(targetLat, targetLon)).vehicle(1);
        // 获取导航控制类
        bikeNavigateHelper = BikeNavigateHelper.getInstance();
    }

    private List<Integer> icons;


    /**
     * 在地图上展示各个点
     *
     * @param pointList
     */
    private void showPointsInBaiduMap(List<LatLng> pointList, Integer resours) {
//        baiduMap.clear();
        if (resours == null) {
            //创建OverlayOptions的集合
            List<OverlayOptions> options = new ArrayList<>();
            for (int i = 0; i < pointList.size(); i++) {
                //构建MarkerOption，用于在地图上添加Marker
                MarkerOptions option = new MarkerOptions();
                option.position(pointList.get(i));
                if (i < icons.size()) {
                    //构建Marker图标
                    option.icon(BitmapDescriptorFactory
                            .fromResource(icons.get(i)));
                } else {
                    option.icon(BitmapDescriptorFactory
                            .fromResource(icons.get(icons.size() - 1)));
                }
                //在地图上添加Marker，并显示
                options.add(option);
                //定义文字所显示的坐标点

            }
            //在地图上批量添加
            baiduMap.addOverlays(options);
        } else {
            //创建OverlayOptions的集合
            List<OverlayOptions> options = new ArrayList<>();
            //构建MarkerOption，用于在地图上添加Marker
            MarkerOptions option = new MarkerOptions();
            option.position(pointList.get(0));
            option.icon(BitmapDescriptorFactory
                    .fromResource(resours));
            //在地图上添加Marker，并显示
            options.add(option);
            //定义文字所显示的坐标点
            //在地图上批量添加
            baiduMap.addOverlays(options);
        }


    }

    @Override
    public void initListener() {
        ivToTrip.setOnClickListener(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CcsApplication.addActivity(this);
        initReceiver();

    }

    /**
     * 注册广播接收者
     */
    private void initReceiver() {
        IntentFilter iFilter = new IntentFilter();
        iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR);
        iFilter.addAction(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR);
        mReceiver = new SDKReceiver();
        registerReceiver(mReceiver, iFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CcsApplication.removeActivity(this);
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        bmapView.onDestroy();
        CcsApplication.getInstance().mLocationClient.stop();
        CcsApplication.getInstance().mLocationClient.unRegisterLocationListener(this);
        mSearch.destroy();
        unregisterReceiver(mReceiver);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        bmapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        bmapView.onPause();
    }

    private String currentCity;

    //定位成功回调函数
    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        if (bdLocation != null) {
            currentLat = bdLocation.getLatitude();
            currentLon = bdLocation.getLongitude();
            currentAdress = bdLocation.getAddrStr();
            currentCity = bdLocation.getCity();
            CcsApplication.getInstance().mLocationClient.stop();
            String queryPlanDtoStr = getIntent().getStringExtra("queryPlanDto");
            this.mQueryPlanDto = JSONObject.parseObject(queryPlanDtoStr, QueryPlanDto.class);
            /**
             * 查询行程规划详情
             */
            initQueryPlanDetail();
            /**
             * 初始化自行车导航
             */
            initBikeNavi();
            /**
             * 初始化步行导航
             */
            initWalkNavi();
        }
    }

    /**
     * 定位到某个坐标点
     *
     * @param latitude
     * @param longitude
     */
    private void initMapLocation(double latitude, double longitude) {
        // 开启定位图层
        baiduMap.setMyLocationEnabled(true);
        // 构造定位数据
        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(200)
                // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(100).latitude(latitude)
                .longitude(longitude).build();
        // 设置定位数据
        baiduMap.setMyLocationData(locData);
        // 设置定位图层的配置（定位模式，是否允许方向信息，用户自定义定位图标）
        BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
                .fromResource(R.drawable.image_now_adress);
        MyLocationConfiguration config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING, true, mCurrentMarker);
        baiduMap.setMyLocationConfiguration(config);
        // 当不需要定位图层时关闭定位图层
        baiduMap.setMyLocationEnabled(false);

    }

    /**
     * 开启定位
     */
    private void startLocationCilent() {
        // 申请权限
        if (android.os.Build.VERSION.SDK_INT >= 23) {
            if (!PermissionUtils.hasPermission(this, authBaseArr)) {
                requestPermissions();
                return;
            }
        }
        CcsApplication.getInstance().mLocationClient.start();
        CcsApplication.getInstance().mLocationClient.registerLocationListener(this);
    }

    //1-已分配，2-已外访，3-已完成，4-已回收
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_to_trip:
                if (status == null) {
                    return;
                }
                if (status != 1) {
                    ToastUtils.showToast("当前外访任务已结束");
                    return;
                }
                showSelecttraffic();
                break;
        }
    }

    private SelectTrrificPopWindow selectTrrificPopWindow;
    private View contentView;

    /**
     * 选择交通工具
     */
    private void showSelecttraffic() {
        selectTrrificPopWindow = new SelectTrrificPopWindow(this, this);
        //底部弹出
        selectTrrificPopWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
    }

    /**
     * /**
     * 步行开始算路导航
     */
    private void routeWalkPlanWithParam() {
        // 引擎初始化
        walkNavigateHelper.initNaviEngine(this, new IWEngineInitListener() {
            @Override
            public void engineInitSuccess() {
                walkNavigateHelper.routePlanWithParams(walkNaviLaunchParam, new IWRoutePlanListener() {
                    @Override
                    public void onRoutePlanStart() {
                    }

                    @Override
                    public void onRoutePlanSuccess() {
                        getLoadingDialog().dismiss();
                        Intent intent = new Intent();
                        intent.setClass(TaskTripMapActivity.this, WalkGuideActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onRoutePlanFail(WalkRoutePlanError error) {
                        getLoadingDialog().dismiss();
                    }

                });
            }

            @Override
            public void engineInitFail() {
                getLoadingDialog().dismiss();
            }
        });

    }

    /**
     * 骑行开始算路导航
     */
    private void routeBikePlanWithParam() {
        // 引擎初始化
        bikeNavigateHelper.initNaviEngine(this, new IBEngineInitListener() {
            @Override
            public void engineInitSuccess() {
                // Logger.d(TAG, "engineInitSuccess: 引擎初始化成功");
                bikeNaviLaunchParam = new BikeNaviLaunchParam().stPt(new LatLng(currentLat, currentLon)).endPt(new LatLng(targetLat, targetLon));
                bikeNavigateHelper.routePlanWithParams(bikeNaviLaunchParam, new IBRoutePlanListener() {
                    @Override
                    public void onRoutePlanStart() {
                        // Logger.d(TAG, "onRoutePlanStart: 开始算路");
                    }

                    @Override
                    public void onRoutePlanSuccess() {
                        getLoadingDialog().dismiss();
                        // Logger.d(TAG, "onRoutePlanSuccess: 算路成功,跳转至诱导页面");
                        Intent intent = new Intent();
                        intent.setClass(TaskTripMapActivity.this, BikeGuideActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onRoutePlanFail(BikeRoutePlanError error) {
                        getLoadingDialog().dismiss();
                        //  Logger.d(TAG, "onRoutePlanFail: 算路失败");
                    }

                });


            }

            @Override
            public void engineInitFail() {
                getLoadingDialog().dismiss();
            }
        });

    }

    /**
     * 车驾导航
     *
     * @param coType
     */
    private void routeBusplanToNavi(BNRoutePlanNode.CoordinateType coType) {
        BNRoutePlanNode sNode = null;
        BNRoutePlanNode eNode = null;
        sNode = new BNRoutePlanNode(currentLon,
                currentLat, currentAdress, null, coType);
        eNode = new BNRoutePlanNode(targetLon,
                targetLat, tvAdress.getText().toString(), null, coType);
        if (sNode != null && eNode != null) {
            List<BNRoutePlanNode> list = new ArrayList<>();
            list.add(sNode);
            list.add(eNode);
            BaiduNaviManager.getInstance().launchNavigator(this, list, 1, true, new DemoRoutePlanListener(sNode), eventListerner);
        }
    }

    public static final String ROUTE_PLAN_NODE = "routePlanNode";
    BaiduNaviManager.NavEventListener eventListerner = new BaiduNaviManager.NavEventListener() {

        @Override
        public void onCommonEventCall(int what, int arg1, int arg2, Bundle bundle) {
        }
    };

    @Override
    public void onItemClick(View view, int position) {
        for (int i = 0; i < lists.size(); i++) {
            if (i == position) {
                lists.get(i).setSelected(true);
            } else {
                lists.get(i).setSelected(false);
            }
        }
        selectPersionAdapter.notifyDataSetChanged();
        initBottomView(position);
    }

    @Override
    public void onSelectTrrifi(int type) {
        selectTrrificPopWindow.dismiss();
        switch (type) {
            //驾车
            case 1:
                if (BaiduNaviManager.isNaviInited()) {
                    //导航到目的地
                    getLoadingDialog().showDialog();
                    routeBusplanToNavi(BNRoutePlanNode.CoordinateType.BD09LL);

                } else {
                    ToastUtils.showToast("初始化导航失败");
                    getLoadingDialog().dismiss();
                }
                break;
            //公交
            case 2:
                if (EmptyUtils.isNotEmpty(addressCity)
                        && EmptyUtils.isNotEmpty(currentCity)
                        && (
                        addressCity.equals(currentCity)
                                || addressCity.contains(currentCity)
                                || currentCity.contains(addressCity)
                )
                        ) {
                    LatLonVo vo = new LatLonVo(currentLat, currentLon, targetLat, targetLon, tvAdress.getText().toString());
                    //EventBus.getDefault().postSticky(vo);
                    Intent intent = new Intent(TaskTripMapActivity.this, BusListPlanActivity.class);
                    intent.putExtra("queryPlanDetailDto", queryPlanDetailDto);
                    intent.putExtra("vo", vo);
                    startActivity(intent);
                } else {
                    ToastUtils.showToast("不能跨城市使用公交路线");
                }

                break;
            case 3:
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                    ToastUtils.showToast("手机系统版本过低，无法使用骑行导航");
                    return;
                }
                //骑行
                getLoadingDialog().showDialog();
                routeBikePlanWithParam();
                break;
        }

    }

    public class DemoRoutePlanListener implements BaiduNaviManager.RoutePlanListener {

        private BNRoutePlanNode mBNRoutePlanNode = null;

        public DemoRoutePlanListener(BNRoutePlanNode node) {
            mBNRoutePlanNode = node;
        }

        @Override
        public void onJumpToNavigator() {
            getLoadingDialog().dismiss();
            Intent intent = new Intent(TaskTripMapActivity.this, BusGuideActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(ROUTE_PLAN_NODE, (BNRoutePlanNode) mBNRoutePlanNode);
            intent.putExtras(bundle);
            startActivity(intent);
        }

        @Override
        public void onRoutePlanFailed() {
            getLoadingDialog().dismiss();
        }
    }


    /**
     * 展示点击地图的ui变化
     *
     * @param latitude
     * @param longitude
     */
    private void showSelectPointView(double latitude, double longitude) {
        for (int i = 0; i < mPointList.size(); i++) {
            if (latitude == mPointList.get(i).latitude && longitude == mPointList.get(i).longitude) {
                initBottomView(i);
            }
        }
        targetLat = latitude;
        targetLon = longitude;
        //定位到某个点
        initMapLocation(latitude, longitude);
    }

    /**
     * 通过经纬度检索地址
     *
     * @param lat
     * @param lon
     */
    private void searchAdressForLatLong(double lat, double lon) {
        mSearch.reverseGeoCode(new ReverseGeoCodeOption()
                .location(new LatLng(lat, lon)));

    }

    /**
     * 地址检索监听器
     */
    OnGetGeoCoderResultListener listener = new OnGetGeoCoderResultListener() {
        public void onGetGeoCodeResult(GeoCodeResult result) {
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                //没有检索到结果
            }
            //获取地理编码结果
            tvAdress.setText(result.getAddress());
        }

        @Override
        public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                //没有找到检索结果
            }
            //获取反向地理编码结果
            //获取地理编码结果
            tvAdress.setText(result.getAddress());
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        MPermissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == ArCameraView.WALK_AR_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_DENIED) {
                ToastUtils.showToast("没有相机权限,请打开后重试");
            } else if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                walkNavigateHelper.startCameraAndSetMapView(TaskTripMapActivity.this);
            }
        }
    }

    //不要删这段代码
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //super.onSaveInstanceState(outState);
    }
}
